$(document).ready(function() {
	userset_fileupload();
	adduser_set_fileupload();
    get_hash();
	$("#strUserBirthDay, #addstrUserBirthDay").datepicker({ 
		changeYear: true,
	});	
	$("#submitUser").click(function(){ 
		saveUsers();
	});	
	$("#add_user_form").click(function(){
		addUserForm();
	});
	$("#addsubmitUser").click(function(){
		addUser();
	});
});
function users(){
	var asort = 0;
	users_icons = {};
	xfunc = "users/list_users";
	
	data_sent = {};
		
		$.ajax({ 
			type: "POST", // request type POST
			url: base_url+xfunc, // post to PHP file
			data: data_sent, // request send to PHP file
			dataType:'json',
			success: function(result){ // result = return from php request
				$(result.intID).each(function(k,v){
					asort = result.intID[k];
					users_icons_panel = '';
						users_icons_panel +='<tr>';;
							users_icons_panel +='<td><img width="86" height="66" class="img-rounded" src="'+base_url+'assets/uploaded/user_img/thumbnail/'+result.strImgLink[k]+'" alt=""/></td>';
							users_icons_panel +='<td>'+result.strName[k]+'</td>';
							users_icons_panel +='<td>'+result.dateBirthday[k]+'</td>';
							users_icons_panel +='<td>'+result.intAge[k]+'</td>';
							users_icons_panel +='<td>'+result.strEmail[k]+'</td>';
							if(result.intPoints[k]!=""){
								users_icons_panel +='<td>'+result.intPoints[k]+'</td>';
							} else {
								users_icons_panel +='<td>0</td>';
							}
							users_icons_panel +='<td class="controls"><div class="btn-group">';
							users_icons_panel +='<button class="btn btn-warning" onclick="javascript:changePermission(\''+result.intID[k]+'\')"><i class="icon-star"></i>Make Admin</button>';
							users_icons_panel +='<button class="btn btn-primary" onclick="javascript:editUser(\''+result.intID[k]+'\')"><i class="icon-edit"></i>Edit</button>';
							users_icons_panel +='<button class="btn btn-danger" onclick="javascript:delUser(\''+result.intID[k]+'\', \''+result.strName[k]+'\')"><i class="icon-trash"></i>Delete</button>';
							users_icons_panel +='</div>';
							users_icons_panel +='<button class="btn btn-info add_user_checklist" onclick="javascript:userChecklist(\''+result.intID[k]+'\')">User Check List</button>';
							users_icons_panel +='</td>';
						users_icons_panel +='</tr>';
						users_icons[result.intID[k]]=users_icons_panel;
				});
				
				users_html_panel = '<table class="table table-striped table-bordered" id="users_table">';
				users_html_panel += '<thead>';
					users_html_panel += '<tr>';
						users_html_panel += '<th class="thumb-photo">Photo</th>';
						users_html_panel += '<th class="note-content">User Name</th>';
						users_html_panel += '<th class="note-title">Birthdate</th>';
						users_html_panel += '<th class="note-title">Age</th>';
						users_html_panel += '<th class="note-title">E-mail Address</th>';
						users_html_panel += '<th class="note-content">User Points</th>';
						users_html_panel += '<th>Control</th>';
					users_html_panel += '</tr>';
				users_html_panel += '</thead>';
				users_html_panel += '<tbody>';
				
				for(x=0;x<=asort;x++){
					if($.trim(users_icons[x])!=""){
						users_html_panel +=users_icons[x];
					}
								
				}		
				users_html_panel += '</tbody>';		
				users_html_panel += '</table>';
				
				$('#users_content').html(users_html_panel);
				$('#users_table').dataTable({
					"sPaginationType": "full_numbers",
					"bLengthChange": false,
					"bSort": false
				});
			}
		});	
}
function userChecklist(userID){
	xfunc = "users/get_user_checklist";
	data_sent = {
			'intUserID':userID
	};
	var asort = 0;
	var html;
	users_icons = {};
	$.ajax({
		type: 'POST',
		url: base_url+xfunc,
		data: data_sent, 
		dataType:'json',
		success: function(result){
			$(result.intID).each(function(k,v){
				for(x=0;x<=result.intID[k];x++){
					asort = result.intID[k];
					users_icons_panel = '';
						users_icons_panel +='<tr>';;
							users_icons_panel +='<td>'+result.strDescription[k]+'</td>';
							//users_icons_panel +='<td>'+result.dateCreatedDate[k]+'</td>';
						users_icons_panel +='</tr>';
					users_icons[result.intID[k]]=users_icons_panel;
				}
			});
			
			users_html_panel = '<table class="table table-striped table-bordered" id="users_checklist">';
			users_html_panel += '<thead>';
				users_html_panel += '<tr>';
					users_html_panel += '<th class="thumb-photo">User Checklist</th>';
					//users_html_panel += '<th class="date">Date</th>';
				users_html_panel += '</tr>';
			users_html_panel += '</thead>';
			users_html_panel += '<tbody>';
			
			for(x=0;x<=asort;x++){
				if($.trim(users_icons[x])!=""){
					users_html_panel +=users_icons[x];
				}
							
			}		
			users_html_panel += '</tbody>';		
			users_html_panel += '</table>';
			$("#users_content, #add_user_form").hide("slide", {direction: "up"}, 100, function(){});
			$("#userChecklist").slideDown('slow', function(){
				$('#user_checklist_content').html(users_html_panel);
			});
			$('#users_checklist').dataTable({
				"sPaginationType": "full_numbers",
				"bLengthChange": false,
				"bSort": false
			});	

			$(".back-btn-userChecklist a").attr("onclick","btn_back_userChecklist()");
		}
	});
}
function addUserForm(){
	$("#users_content, #add_user_form").hide();
	$("#addUsers").slideDown('slow', function(){
		$("#users_content").hide();
		$("#addUsers").slideDown('slow', function(){
			$(".back-btn-adduser a").attr("onclick","btn_back_adduser()");
		});	
	});	
}
function addUser(){
	var thumbnailLink = $("#adduser_thumbnailLink").val();
	var addstrUserName = $("#addstrUserName").val();
	var addstrUserBirthDay = $("#addstrUserBirthDay").val();
	var addstrUserEmail = $("#addstrUserEmail").val();
	//var addstrUserPoint = $("#addstrUserPoint").val();
	var addstrPassword = $("#addstrPassword").val();

	bDate = addstrUserBirthDay.split("/");
	
	var today = new Date(); 
    var birthDate = new Date(bDate); 
    var age = today.getFullYear() - birthDate.getFullYear(); 
    var m = today.getMonth() - birthDate.getMonth(); 

    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { 
        age--; 
    }
	var ageUser = age;  
	birthDate = bDate[2]+'-'+bDate[0]+'-'+bDate[1];  
	
	if(thumbnailLink==''){
		$("#errorUsers").html("<div class='alert alert-error'>Error: Put the photo of user!</div>");
	} else if(addstrUserName=='') {
		$("#errorUsers").html("<div class='alert alert-error'>Error: Put the name of user!</div>");
	} else if(addstrUserBirthDay=='') {
		$("#errorUsers").html("<div class='alert alert-error'>Error: Put the age of user!</div>");
	} else if(addstrUserEmail=='') {
		$("#errorUsers").html("<div class='alert alert-error'>Error: Put the e-mail!</div>");
	//} else if(addstrUserPoint=='') {
	//	$("#errorUsers").html("<div class='alert alert-error'>Error: Put the userpoint!</div>");
	} else {
		xfunc = "users/add_user";
		data_sent = {
				'strUserName':addstrUserName,
				'strBirthDay':birthDate,
				'ageUser':ageUser,
				'strPassword':addstrPassword,
				'strUserEmail':addstrUserEmail,
				//'strUserPoint':addstrUserPoint,
				'strImgLink':thumbnailLink
		};
		//console.log(birthDate);
		$.ajax({
			type: 'POST',
			url: base_url+xfunc,
			data: data_sent, 
			dataType:'json',
			success: function(result){
				$("#errorUsers").hide();
				$("#addUsersSuccess").html('<div class="alert alert-success">Data was successfully saved!</div>');
				
				$("#thumbnailLink").val('');
				$("#addstrUserName").val('');
				$("#addstrUserBirthDay").val('');
				$("#addstrUserEmail").val('');
				//$("#addstrUserPoint").val('');
				$(".alert-success").fadeOut(5000);
			}
		});
	}
}
function editUser(noteID){
	xfunc = "users/get_user_data";
	data_sent = {
			'intID':noteID
	};
	$.ajax({
		type: 'POST',
		url: base_url+xfunc,
		data: data_sent, 
		dataType:'json',
		success: function(result){
			bDate = result.dateBirthday.split("-");
			birthDate = bDate[1]+'/'+bDate[2]+'/'+bDate[0];
			var users_thumbnail = '<div class="imgThumbnail"><img width="86" class="img-rounded" src="'+base_url+'assets/uploaded/user_img/thumbnail/'+result.strImgLink+'" alt=""/></div>';
			$("#intUID").val(result.intID);
			//$("#strUserPoint").val(result.intPoints);
			$("#strUserName").val(result.strName);
			$("#strUserBirthDay").val(birthDate);
			$("#strUserEmail").val(result.strEmail);
			$("#user_thumbnail").html(users_thumbnail);
			$("#user_thumbnailLink").val(result.strImgLink);
		}
	});

	$("#add_user_form").hide();
	$("#users_content").hide();
	$("#editUsers").slideDown('slow', function(){
		$(".back-btn-user a").attr("onclick","btn_back_user()");
	});	
}

function saveUsers(){
	var intID = $("#intUID").val();
	//var strUserPoint = $("#strUserPoint").val();
	var strUserName = $("#strUserName").val();
	var strBirthDay = $("#strUserBirthDay").val();
	var strUserEmail = $("#strUserEmail").val();
	var strImgLink = $("#user_thumbnailLink").val();
	var strPassword = $("#strPassword").val();

	bDate = strBirthDay.split("/");
	
	var today = new Date(); 
    var birthDate = new Date(bDate); 
    var age = today.getFullYear() - birthDate.getFullYear(); 
    var m = today.getMonth() - birthDate.getMonth(); 

    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { 
        age--; 
    }
	var ageUser = age;  
	birthDate = bDate[2]+'-'+bDate[0]+'-'+bDate[1];  
	
	xfunc = "users/save_users";
	data_sent = {
			'intID':intID,
			//'strUserPoint':strUserPoint,
			'strUserName':strUserName,
			'ageUser':ageUser,
			'strPassword':strPassword,
			'strBirthDay':birthDate,
			'strUserEmail':strUserEmail,
			'strImgLink':strImgLink
	};
	$.ajax({
		type: 'POST',
		url: base_url+xfunc,
		data: data_sent, 
		dataType:'json',
		success: function(result){
			$("#userSuccess").html('<div class="alert alert-success">Data was successfully updated!</div>');
			$(".alert-success").fadeOut(5000);
		}
	});
}
function delUser(noteID, titleName){
	xfunc = "users/delete_user";
	data_sent = {
			'intID':noteID
	};
	$('#label-delete').html(titleName);
    $('#deleteModal').modal('show');
    $('button#confirm').click(function(e){
        $('#deleteModal').modal('hide');
		
		$.ajax({
			type: 'POST',
			url: base_url+xfunc,
			data: data_sent, 
			dataType:'json',
			success: function(result){
				users();
			}
		});
    });
}
function changePermission(intID){
	xfunc = "users/change_perm_user";
	data_sent = {
			'intID':intID
	};
		
	$.ajax({
		type: 'POST',
		url: base_url+xfunc,
		data: data_sent, 
		dataType:'json',
		success: function(result){
			users();
		}
	});
}
function btn_back_userChecklist(){
	$("#userChecklist").hide();
	$("#users_content").slideDown('fast', function(){
		$("#add_user_form").show();
		users();
	});	
}
function btn_back_adduser(){
	$("#addUsers").hide();
	$("#users_content").slideDown('fast', function(){
		$("#add_user_form").show();
		users();
	});	
}
function btn_back_user(){
	$("#editUsers").hide();
	$("#users_content").slideDown('fast', function(){
		$("#add_user_form").show();
		users();
	});	
}
function userset_fileupload(){
	$('#user_input_fileupload').attr('data-url',base_url+'assets/lib/jquery.fileupload/server/php/index.php');
	userfile_upload();
}
function userfile_upload(){
	$('.user_fileupload').fileupload();
	$('.user_fileupload').fileupload('option',{
		dataType: 'json',
		maxFileSize: 20000000, //20MB
		acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,			
		done: function (e, data) {
			$.each(data.result, function (index, file) {
				$.each(file, function (k, v) {		
					html = '<img width="86" class="img-rounded" src="'+base_url+"assets/uploaded/user_img/thumbnail/"+v.name+'" />';
					$("#user_thumbnailLink").val(v.name);			
					$(".imgThumbnail").hide();
					$(".imgThumbnail").slideDown('slow', function(){
						$(".imgThumbnail").html(html);
					});					
				});
			});
		}
	}).bind('fileuploadfailed', function (e, data) {
		$(".result-message-box").html("Upload Error!");
	});		
}
//ADD DATA
function adduser_set_fileupload(){
	$('#adduser_input_fileupload').attr('data-url',base_url+'assets/lib/jquery.fileupload/server/php/index.php');
	adduser_file_upload();
}
function adduser_file_upload(){
	$('.adduser_fileupload').fileupload();
	$('.adduser_fileupload').fileupload('option',{
		dataType: 'json',
		maxFileSize: 20000000, //20MB
		acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,			
		done: function (e, data) {
			$.each(data.result, function (index, file) {
				$.each(file, function (k, v) {		
					html = '<img width="86" class="img-rounded" src="'+base_url+"assets/uploaded/user_img/thumbnail/"+v.name+'" />';
					$("#adduser_thumbnailLink").val(v.name);			
					$("#adduser_thumbnail").html(html);			
				});
			});
		}
	}).bind('fileuploadfailed', function (e, data) {
		$(".result-message-box").html("Upload Error!");
	});		
}